package com.ay.wiki_planet.service;

import com.ay.wiki_planet.domain.Ebook;
import com.ay.wiki_planet.domain.EbookExample;
import com.ay.wiki_planet.mapper.EbookMapper;
import com.ay.wiki_planet.req.EbookQueryReq;
import com.ay.wiki_planet.req.EbookSaveReq;
import com.ay.wiki_planet.resp.EbookQueryResp;
import com.ay.wiki_planet.resp.PageResp;
import com.ay.wiki_planet.util.CopyUtil;
import com.ay.wiki_planet.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class EbookService {

    @Resource
    private EbookMapper ebookMapper;


    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        //动态sql 判断名字不为空则加上条件查询
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);


        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        log.info("总行数:{}", pageInfo.getTotal());
        log.info("总页数:{}", pageInfo.getPages());
        //pageInfo.getTotal(); 总行数
        //pageInfo.getPages(); 总页数

        //将List<Ebook>变成List<EbookResp>
        //List<EbookResp> respList = new ArrayList<>();
        //for(Ebook ebook : ebookList){
        //    //实现对象的复制
        //    //EbookResp ebookResp = new EbookResp();
        //    //BeanUtils.copyProperties(ebook,ebookResp);
        //
        //    EbookResp ebookResp = CopyUtil.copy(ebook, EbookResp.class);
        //    respList.add(ebookResp);
        //}


        //列表复制
        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /*
     * 保存
     * */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    /*
     * 删除
     * */
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }


}
